package com.ravi.controller;

import com.ravi.common.R;
import com.ravi.core.queue.HashQueueManager;
import com.ravi.entity.CheckArea;
import com.ravi.entity.CheckRoom;
import com.ravi.service.CheckAreaService;
import com.ravi.service.PatientQueueInfoService;
import com.ravi.util.jwt.JWTUtils;
import com.ravi.vo.AreaRoomVo;
import com.ravi.vo.AreaStatisticalVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("area")
@Slf4j
public class AreaController {

	@Autowired
	private CheckAreaService checkAreaService;

	/**
	 * 查询所有的检查区
	 * @return List<CheckArea>
	 */
	@GetMapping("all")
	public List<CheckArea> getAll(){
		return checkAreaService.getAllCheckAreas();
	}

	/**
	 * 通过解析Token得到areaId进而得到AreaRoomVo，即一个检查区有哪些检查室的信息
	 * @return
	 */
	@GetMapping("areaRooms")
	public R getAreaRooms(HttpServletRequest request) {
		final Integer areaId = JWTUtils.getAreaId(request.getHeader("token"));
		try{
			AreaRoomVo areaRoomVo = checkAreaService.getAreaInfoById(areaId);
			return R.ok().put("areaRooms", areaRoomVo);
		}catch (Exception e) {
			return R.error(e.getMessage());
		}
	}

	@Autowired
	private PatientQueueInfoService patientQueueInfoService;

	@GetMapping("statistical")
	public R getStatisticalValue(HttpServletRequest request) {
		final Integer areaId = JWTUtils.getAreaId(request.getHeader("token"));
//		String[] constants = new String[] {"全部", "大厅", "完成", "过号", "暂停"};
		int SystemTotalCount = patientQueueInfoService.getPatientTotal();
		int areaTotalCount = 0;
		int finishedCount = 0;
		int missCount = 0;
		int suspendedCount = 0;
		AreaRoomVo areaRoomVo = checkAreaService.getAreaInfoById(areaId);
		List<CheckRoom> rooms = areaRoomVo.getRooms();
		for (CheckRoom room : rooms) {
			areaTotalCount += HashQueueManager.getQueue(room.getRoomId()).size();
		}
		AreaStatisticalVo SystemState = new AreaStatisticalVo("全部", SystemTotalCount);
		AreaStatisticalVo AreaState = new AreaStatisticalVo("大厅", areaTotalCount);
		AreaStatisticalVo finishedState = new AreaStatisticalVo("完成", finishedCount);
		AreaStatisticalVo missState = new AreaStatisticalVo("过号", missCount);
		AreaStatisticalVo suspendedState = new AreaStatisticalVo("暂停", suspendedCount);
		ArrayList<AreaStatisticalVo> resData = new ArrayList<>();
		resData.add(SystemState);
		resData.add(AreaState);
		resData.add(finishedState);
		resData.add(missState);
		resData.add(suspendedState);
		return R.ok().put("stateArray", resData);
	}

}
